﻿#include "elk_browser_app.h"
#include <QFile>
#include <QLocale>

static char languages[][8] = {
    {"en-US"},
    {"zh-CN"}
};

ElkBrowserApp::ElkBrowserApp(ElkApplication *elk_application) :
    elk_application_(elk_application)
{
    LOG(INFO) << "ElkBrowserApp()";
}

ElkBrowserApp::~ElkBrowserApp()
{
    LOG(INFO) << "~ElkBrowserApp()";
}

bool ElkBrowserApp::Initialize()
{
    std::string app_path = QCoreApplication::applicationDirPath().toStdString();
    std::string cache_path = app_path + std::string("/cache");
    std::string subprocess_path = app_path + std::string("/elk-subprocess.exe");

    if (!QFile::exists(QString(subprocess_path.c_str()))) {
        exit(-1);
    }

    int lang = 0;
    QLocale locale;
    if (locale.language() == QLocale::Chinese) {
        lang = 1;
    }

    CefMainArgs args;
    CefSettings settings;
    settings.external_message_pump = 1;
    settings.multi_threaded_message_loop = 0;
    settings.remote_debugging_port = 8181;
    settings.log_severity = LOGSEVERITY_INFO;
    cef_string_from_utf8(languages[lang], strlen(languages[lang]), &settings.locale);
    cef_string_from_utf8(cache_path.c_str(), cache_path.length(), &settings.cache_path);
    cef_string_from_utf8(subprocess_path.c_str(), subprocess_path.length(), &settings.browser_subprocess_path);
    return CefInitialize(args, settings, this, nullptr);
}

void ElkBrowserApp::ShutDown()
{
    LOG(INFO) << "ShutDown()";
    CefShutdown(); //退出前需确保所有CefBrowser已经释放，否则会造成崩溃现象或进程无法退出
}

void ElkBrowserApp::DoMsgLoopWork()
{
    CefDoMessageLoopWork();
}

void ElkBrowserApp::OnContextInitialized()
{
    LOG(INFO) << "OnContextInitialized()";
}

void ElkBrowserApp::OnScheduleMessagePumpWork(int64 delay_ms)
{
    if (delay_ms <= 0) {
        emit elk_application_->msgWorkScheduled(ElkApplication::QPrivateSignal());
    }
}
